package com.swt.gap.util;

import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

import java.io.*;

/**
 * @author zqw
 * @date 2020/6/5 13:37
 */
public class SvgUtils {

    /**
     * svg转换成图片
     * @param svg svg文件对象
     * @param png 要写成png的文件对象
     * @throws IOException
     * @throws TranscoderException
     */
    public static void convertSvg2Png(File svg, File png) throws IOException, TranscoderException {

        InputStream in = new FileInputStream(svg);
        OutputStream out = new FileOutputStream(png);
        out = new BufferedOutputStream(out);

        Transcoder transcoder = new PNGTranscoder();
        try {
            TranscoderInput input = new TranscoderInput(in);
            try {
                TranscoderOutput output = new TranscoderOutput(out);
                transcoder.transcode(input, output);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }

    /**
     * svg字符串转换成图片
     * @param svgStr svg字符串信息
     * @param pngPath 要转成的图片的路径（注意没有做同名文件的校验）
     * @throws IOException
     * @throws TranscoderException
     */
    public static void parseSvg2Png(String svgStr, String pngPath) throws IOException, TranscoderException {

        InputStream in = new ByteArrayInputStream(svgStr.getBytes());
        OutputStream out = new FileOutputStream(new File(pngPath));
        out = new BufferedOutputStream(out);

        Transcoder transcoder = new PNGTranscoder();
        try {
            TranscoderInput input = new TranscoderInput(in);
            try {
                TranscoderOutput output = new TranscoderOutput(out);
                transcoder.transcode(input, output);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }
}
